<template>
  <el-dialog :title="!dataForm.id ? '采购订单新增':'采购订单修改'" :close-on-click-modal="false" :visible.sync="visible" center fullscreen>
    <el-button class="miui-dialog-close-btn" @click="visible = false">关闭页面</el-button>
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" label-width="120px">
      <el-row>
        <el-col :span="8">
          <el-form-item label="采购类型" prop="ctgId">
            <el-select v-model="dataForm.ctgId" @change="ctgSelectChange($event)">
              <el-option v-for="item in ctgOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="制造商" prop="supplyName">
            <el-input v-model="dataForm.supplyName"  readonly>
              <el-button slot="append" @click="checkSupplyList">选择</el-button>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="调拨申请单号" prop="linkBillId">
            <el-input v-model="dataForm.linkBillId">
              <el-button slot="append" >选择</el-button>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="memo">
            <el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="dataForm.memo"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-form :inline="true">
      <el-form-item><el-button type="primary" @click="addGoodsBySingle">单品添加商品</el-button></el-form-item>
      <!-- <el-form-item><el-button type="primary">条码扫描</el-button></el-form-item> -->
      <el-form-item style="float: right;"><el-button type="danger" @click="delTableData">删除</el-button></el-form-item>
    </el-form>
    <ctg-form ref="ctgFormDialog" :ctgId="dataForm.ctgId" :dataList="dataList" :loading="dataListLoading" @refreshData="handleSelectionChange" :frameMaterialData="frameMaterialData"></ctg-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">关闭</el-button>
      <el-button type="primary" @click="dataFormSubmit" :loading="ischeck" v-prevent-re-click>保存</el-button>
      <el-switch v-model="dataForm.applyStatus" active-text="保存并审核" inactive-value="0" active-value="1" style="margin-left: 15px;"></el-switch>
    </span>
    <supply-search v-if="supplySearchVisible" ref="supplySearch" @refreshData="renewFormData"></supply-search>
    <goods-list v-if="goodsListVisible" ref="sinleGoodsList" @updateForm="updateFormData" :ctgList="ctgOptions"></goods-list>
  </el-dialog>
</template>

<script>
    import {receiveApplyGetObj, receiveApplyAddObj, receiveApplyPutObj} from '@/api/eims/purchase/receive-apply'
    import { getCtgList } from '@/api/eims/ctg'
    import { remote } from '@/api/admin/dict'
    import GoodsList from '@/components/business/goods-search-single'
    import SupplySearch from '@/components/business/SearchSupply'
    import CtgForm from '../CtgForm'
    export default {
    data () {
      return {
        ischeck: false,
        visible: false,
        frameMaterialData: [],
        dataForm: {
          id: 0,
          applyStatus: '0',
          ctgId: '',
          ctgName: '',
          supplyId: '',
          supplyName: '',
          memo: '',
          detailList: []
        },
        ctgOptions: [],
        dataList: [],
        dataListLoading: false,
        dataRule: {ctgId: [{ required: true,message: '请选择采购类别'}],supplyName: [{required:true,message: '请选择制造商'}]},
        supplySearchVisible: false,
        goodsListVisible: false,
        selectionList: []
      }
    },
    components: {
      GoodsList,
      SupplySearch,
      CtgForm
    },
    methods: {
      init (id) {
        remote('frame_material').then(result => {
          this.frameMaterialData = result.data.data
        })
        this.getCtgList()
        this.dataForm.id = id || 0
        this.dataForm.supplyId = ''
        this.dataForm.applyStatus = '0'
        this.visible = true
        this.dataList = []
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            receiveApplyGetObj(this.dataForm.id).then(response => {
              if(response.data.code == '0'){
               this.dataForm = response.data.data.data
               this.dataList = response.data.data.data.detailList
               if(this.dataList){
                 this.dataList.forEach(item => {
                   item.code = item.goodsCode
                   item.name = item.goodsName
                 })
               }
              }else{
                this.$message.error(response.data.msg)
              }
            })
          }

        })
      },
      // 商品类别改变时获取名字
      ctgSelectChange ($event) {
        this.dataForm.supplyId = ''
        this.dataForm.supplyName = ''
        this.dataForm.detailList = []
        this.dataList = []
        this.ctgOptions.forEach(item => {
          if(item.value == $event){ this.dataForm.ctgName = item.name }
        })
      },
      // 打开制造商列表弹窗
      checkSupplyList () {
        if(this.dataForm.ctgId) {
          let data = { ctgId: this.dataForm.ctgId }
          this.supplySearchVisible = true
          this.$nextTick(() => {
            this.$refs.supplySearch.init(data)
          })
        }else{
          this.$message.warning('请选择采购类型')
        }

      },
      // 选择制造商
      renewFormData (data) {
        this.dataForm.supplyId = data.id
        this.dataForm.supplyName = data.name
      },
      // 打开商品列表弹窗
      addGoodsBySingle() {
        // 判断是否选中采购类型
        if(!this.dataForm.ctgId){
          this.$message.warning('请选择采购类型')
          return
        }
        // 判断是否选中制造商
        if(!this.dataForm.supplyId){
          this.$message.warning('请选择制造商')
          return
        }
        let params = {ctgId:this.dataForm.ctgId,supplyId:this.dataForm.supplyId,ctgName: this.dataForm.ctgName,supplyName: this.dataForm.supplyName}
        let data = {params: params,data: this.dataList,disable: true}
        this.goodsListVisible = true
        this.$nextTick(() => {  this.$refs.sinleGoodsList.init(data) })
      },
      handleSelectionChange(val) {
        this.selectionList = val
      },
      // 删除选中的商品
      delTableData() {
        let arrIdList = this.selectionList.map(x => x.id)
        this.dataList = this.dataList.filter(x => !arrIdList.includes(x.id))
        this.$refs.multipleTable.clearSelection()
      },
      //更新表单数据
      updateFormData(data) {
        this.dataList = JSON.parse( JSON.stringify(data) )
        let list = []
        data.forEach(item => {
          item.goodsId = item.id
          list.push(item)
        })
        this.dataForm.detailList = list
      },
      // 表单提交
      dataFormSubmit () {
        this.ischeck = true
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.dataForm.detailList.forEach((item,index) => {
              item.applyQuantity = this.dataList[index].applyQuantity
              item.memo = this.dataList[index].memo
            })
            if(this.dataForm.id){
              receiveApplyPutObj(this.dataForm).then(response =>  {
                if(response.data.code == '0'){
                  (this.dataForm.applyStatus == '1') ? this.$message.success('修改并审核成功') : this.$message.success('修改成功')
                  this.visible = false
                  this.$emit('refreshDataList')
                }else{
                  this.$message.error(response.data.msg)
                }
                this.ischeck = false
              }).catch(() => {
                this.ischeck = false
              })
            }else{
              receiveApplyAddObj(this.dataForm).then(response => {
                if(response.data.code == '0'){
                  (this.dataForm.applyStatus == '1') ? this.$message.success('新增并审核成功') : this.$message.success('新增成功')
                  this.visible = false
                  this.$emit('refreshDataList')
                }else{
                  this.$message.error(response.data.msg)
                }
                this.ischeck = false
              }).catch(() => {
                this.ischeck = false
              })
            }
          }else{
            this.ischeck = false
          }
        })
      },

      /*
      * *  获取采购类型列表
      */
     getCtgList(){
       getCtgList().then(response => {
         if(response.data.code == '0'){
           this.ctgOptions = response.data.data
         }else{
           this.$message.error(response.data.msg)
         }
       })
     }
    }
  }
</script>
